import { mapGetters } from "vuex";
export default {
  data() {
    return {
      $$menuCode$$: "",
    };
  },
  computed: {
    ...mapGetters(["currentMenu"]),
  },
  watch: {
    currentMenu: {
      handler(val) {
        this.$$menuCode$$ = val?.menuCode || "";
      },
      immediate: true,
    },
  },
  beforeRouteLeave(to, from, next) {
    let { meta } = this.$route;
    //是否缓存
    if (this.$vnode && this.$vnode.data.keepAlive) {
      if (
        this.$vnode.parent &&
        this.$vnode.parent.componentInstance &&
        this.$vnode.parent.componentInstance.cache
      ) {
        if (this.$vnode.componentOptions) {
          let { $$menuCode$$, currentMenu } = this;
          if (
            ($$menuCode$$ && $$menuCode$$ != currentMenu?.menuCode) ||
            !meta?.keepAlive
          ) {
            this.removeKeepAliveCacheForVueInstance(this);
          }
        }
      }
    }
    next();
  },
  methods: {
    removeKeepAliveCacheForVueInstance(vueInstance) {
      let key =
        vueInstance.$vnode.key ??
        vueInstance.$vnode.componentOptions.Ctor.cid +
          (vueInstance.$vnode.componentOptions.tag
            ? `::${vueInstance.$vnode.componentOptions.tag}`
            : "");
      let cache = vueInstance.$vnode.parent.componentInstance.cache || {};
      var keys = vueInstance.$vnode.parent.componentInstance.keys;
      if (cache[key]) {
        vueInstance.$destroy();
        delete cache[key];
        let index = keys.indexOf(key);
        if (index > -1) {
          keys.splice(index, 1);
        }
      }
    },
  },
};
